package vip.ola.pay.channel.code;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.IPUtility;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.RedisUtil;
import vip.ola.core.entity.PayOrder;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.service.RpcCommonService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static vip.ola.core.common.constant.CacheKey.ORDER_PAY;
import static vip.ola.core.common.constant.CodeConstant.OPERATE_PHASE_PAY;

@Controller
@RequestMapping("/api/code")
public class CodePayController extends BaseController {

    private static final MyLog _log = MyLog.getLog(CodePayController.class);

    @Value("${config.payUrl}")
    protected String payUrlDomain;
    @Autowired
    private RpcCommonService rpcCommonService;
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("pay_{type}.htm")
    public String toPay(HttpServletRequest request, @PathVariable("type") String type) {
        String orderNo = request.getParameter("orderNo");
        JSONObject object = redisUtil.get(ORDER_PAY + orderNo);
        if (object == null) {
            request.setAttribute("expire", 1);
        } else {
            int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(orderNo, null);
            _log.info("更新订单状态为支付中: orderNo={}, result={}", orderNo, result);
            request.setAttribute("expire", 0);
            request.setAttribute("orderNo", object.getString("orderNo"));
            request.setAttribute("mchOrderNo", object.getString("mchOrderNo"));
            request.setAttribute("amount", object.getString("amount"));
            request.setAttribute("codeUrl", object.getString("codeUrl"));
            request.setAttribute("collThirdName", object.getString("collThirdName"));
            request.setAttribute("collThirdAccount", object.getString("collThirdAccount"));
            request.setAttribute("collThirdId", object.getString("collThirdId"));
            String loadingUrl = payUrlDomain + "/code/loading.htm?orderNo=" + object.getString("orderNo");
            request.setAttribute("loadingUrl", loadingUrl);
            request.setAttribute("createTime", object.getString("createTime"));
        }
        return "payment/code/" + type;
    }

    @RequestMapping("loading.htm")
    public String loading(HttpServletRequest request) {
        String orderNo = request.getParameter("orderNo");
        JSONObject object = redisUtil.get(ORDER_PAY + orderNo);
        if (object == null) {
            request.setAttribute("expire", 1);
        } else {
            rpcCommonService.codeOrderService.updateOperatePhase(orderNo, OPERATE_PHASE_PAY, null, null);
            request.setAttribute("expire", 0);
            request.setAttribute("orderNo", object.getString("orderNo"));
            request.setAttribute("mchOrderNo", object.getString("mchOrderNo"));
            request.setAttribute("amount", object.getString("amount"));
            request.setAttribute("codeUrl", object.getString("codeUrl"));
            request.setAttribute("collThirdName", object.getString("collThirdName"));
            request.setAttribute("collThirdAccount", object.getString("collThirdAccount"));
            request.setAttribute("collThirdId", object.getString("collThirdId"));
        }
        return "payment/code/loading";
    }

    @RequestMapping("/phase")
    @ResponseBody
    public String phase(HttpServletRequest request) {
        String orderNo = request.getParameter("orderNo");
        String type = request.getParameter("type");
        String device = request.getParameter("device");
        String clintIp = IPUtility.getClientIp(request);
        try {
            rpcCommonService.codeOrderService.updateOperatePhase(orderNo, Integer.parseInt(type), clintIp, device);
        } catch (Exception e) {
            _log.error("updateOperatePhase error.", e);
        }

        return "";
    }

    /**
     * 订单查询
     *
     * @param request
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("query")
    @ResponseBody
    public String toQuery(HttpServletRequest request) {
        JSONObject po = getJsonParam(request);
        String payOrderId = getString(po, "payOrderId");
        _log.info("[查询订单]参数payOrderId={}", payOrderId);

        PayOrder payOrder = rpcCommonService.rpcPayOrderService.findByPayOrderId(payOrderId);
        JSONObject retObj = new JSONObject();
        String status = "-1";
        String url = "";
        if (payOrder != null) {
            status = payOrder.getStatus() + "";
            url = payOrder.getReturnUrl();
        }
        retObj.put("status", status);
        retObj.put("url", url);
        _log.info("[查询订单]结果payOrderId={},retObj={}", payOrderId, retObj);
        return retObj.toJSONString();
    }
}
